/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Servlet.user;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import server.process.LimitationException;
import server.process.ProcessBeanLocal;

/** */
public class doUploadCategory extends HttpServlet {
      /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String description ="";
        String fromPage ="";
        String ktimage = "";
        String Categoryname ="";
        String catid="";
        try {

            if (!ServletFileUpload.isMultipartContent(request)) {
                throw new RuntimeException("Upload failed");
            }
            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List fileItemsList = servletFileUpload.parseRequest(request);
            FileItem fileItem = null;
            Iterator it = fileItemsList.iterator();
            while (it.hasNext()) {
                FileItem fileItemTemp = (FileItem) it.next();
                if (fileItemTemp.isFormField()) {
                    if (fileItemTemp.getFieldName().equals("txtDescription")) {
                         description = fileItemTemp.getString();
                    }
                    else if (fileItemTemp.getFieldName().equals("txtColName")) {
                         Categoryname = fileItemTemp.getString();
                    }
                    else if(fileItemTemp.getFieldName().equals("fromPage"))
                    {
                        fromPage = fileItemTemp.getString();
                    }
                    else if(fileItemTemp.getFieldName().equals("ktimage"))
                    {
                      ktimage = fileItemTemp.getString();
                    }else if (fileItemTemp.getFieldName().equals("id")){
                        catid=fileItemTemp.getString();
                    }
                } else {
                    fileItem = fileItemTemp;
                }
            }
            if (fileItem == null) {
                //fileupload is empty
            }
            String filename = fileItem.getName();
            System.out.println(filename);
            //bug for IE
            File fIE = new File(filename);
            if (fIE.isFile()){
                filename=fIE.getName();
            }
            //
            ServletConfig config = getServletConfig();
            String RealPath = config.getServletContext ().getRealPath ("/");
            System.out.println(RealPath);
            String dir = "CategoryImage"+"/";
            if (fileItem.getSize() > 0) {
                String dirname = RealPath+dir+"\\";
                File saveto = new File(dirname + filename);
                fileItem.write(saveto);
                System.out.println(saveto);
            }

//            try{
//            local.createNewCollection(Categoryname, description,session.getAttribute("username").toString(), admin,photoname);
//            }catch (Exception ex){
//                out.println(ex);
//                return;
//            }
            
            
            if(fromPage.equals("newcolection"))
            {
                HttpSession season = request.getSession();
               String username = season.getAttribute("username").toString();
               boolean addmin = false;
               Context context = new InitialContext();
               Object obj = context.lookup("ProcessLocalJNDI");
               ProcessBeanLocal local = (ProcessBeanLocal) obj;
               if(local.createNewCollection(Categoryname,description , username, addmin, filename))
               {
                    out.print("success");
               }
            }
            else if(fromPage.equals("newcolectionAdmin"))
            {
                boolean addmin = true;
               Context context = new InitialContext();
               Object obj = context.lookup("ProcessLocalJNDI");
               ProcessBeanLocal local = (ProcessBeanLocal) obj;
               if(local.createNewCollection(Categoryname,description ,null, addmin, filename))
               {
                    out.print("success");
                }
            }
            else if(fromPage.equals("updatecolectionAdmin"))
            {
              boolean addmin = true;
               Context context = new InitialContext();
               Object obj = context.lookup("ProcessLocalJNDI");
               ProcessBeanLocal local = (ProcessBeanLocal) obj;
               if(filename.isEmpty())
               {
                    if(local.Updatecategory(catid,Categoryname , description,null, addmin,ktimage))
                    {
                        out.print("success");
                    }
               }
               else
               {
                    if(local.Updatecategory(catid,Categoryname , description,null, addmin,filename))
                    {
                        out.print("success");
                    }
               }

            }
            else if(fromPage.equals("updatecolection"))
            {
                HttpSession seasion = request.getSession();
                String username = seasion.getAttribute("username").toString();
              boolean addmin = false;
               Context context = new InitialContext();
               Object obj = context.lookup("ProcessLocalJNDI");
               ProcessBeanLocal local = (ProcessBeanLocal) obj;
               if(filename.isEmpty())
               {
                    if(local.Updatecategory(catid,Categoryname , description,username, addmin,ktimage))
                    {
                        out.print("success");
                    }
               }
               else
               {
                    if(local.Updatecategory(catid,Categoryname , description,username, addmin,filename))
                    {
                        out.print("success");
                    }
               }

            }
        } catch (FileUploadException ex) {
            Logger.getLogger(doUpload.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(doUpload.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
   

